<template>
  <div>
    <h1>角色菜单管理</h1>
    <div v-for="role in roles" :key="role">
      <h2>{{ role }} 角色菜单</h2>
      <el-button @click="toggleDialog(role, 'assign')">给 {{ role }} 分配权限</el-button>
      <el-row>
        <el-col :span="12">
          <el-tree
            ref="roleTreeRef"
            :data="getRoleMenus(role)"
            :props="treeProps"
            node-key="id"
            show-checkbox
            :expand-on-click-node="false"
            @check-change="handleCheckChange"
          >
            <template #default="{ node, data }">
              <span>{{ data.name }}</span>
            </template>
          </el-tree>
        </el-col>
      </el-row>
    </div>

    <!-- 角色菜单操作对话框 -->
    <el-dialog v-model="dialogVisible" title="角色菜单操作">
      <template #default>
        <p>您正在给 {{ currentRole }} 角色分配权限</p>
        <el-tree
          ref="dialogTreeRef"
          :data="menuStore.menuTreeData"
          :props="treeProps"
          node-key="id"
          show-checkbox
          :expand-on-click-node="false"
          @check-change="handleCheckChange"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
          </template>
        </el-tree>
      </template>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAssign">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useRoleMenuStore } from '@/stores/roleMenuStore';
import { useMenuStore } from '@/stores/menuStore';
import { showNotification } from '@/utils/notify';
import type { DoAssignParams } from '@/types/menu';

const roleMenuStore = useRoleMenuStore();
const menuStore = useMenuStore();
const roles = ['ADMIN', 'STU', 'TEACH'];
const dialogVisible = ref(false);
const currentRole = ref('');
const selectedMenuIds = ref<string[]>([]); // 存储用户选择的菜单 ID
const roleTreeRef = ref(null);
const dialogTreeRef = ref(null);

const toggleDialog = (role: string, action: string) => {
  dialogVisible.value = true;
  currentRole.value = role;
  selectedMenuIds.value = []; // 每次打开对话框时清空已选菜单 ID

  // 获取当前角色已有的菜单 ID
  const roleMenus = getRoleMenus(role);
  const roleMenuIds = roleMenus.map(menu => menu.id.toString());

  // 遍历所有菜单数据，将当前角色已有的菜单勾选上
  const allMenus = menuStore.menuTreeData;
  const checkMenu = (menus: any[]) => {
    menus.forEach(menu => {
      if (roleMenuIds.includes(menu.id.toString())) {
        if (!selectedMenuIds.value.includes(menu.id.toString())) {
          selectedMenuIds.value.push(menu.id.toString());
        }
      }
      if (menu.children && menu.children.length > 0) {
        checkMenu(menu.children);
      }
    });
  };
  checkMenu(allMenus);

  nextTick(() => {
    if (dialogTreeRef.value) {
      dialogTreeRef.value.setCheckedKeys(selectedMenuIds.value);
    }
  });
};

// 树状结构属性配置
const treeProps = ref({
  children: 'children',
  label: 'name'
});

// 根据角色获取对应的菜单数据
const getRoleMenus = (role: string) => {
  switch (role) {
    case 'ADMIN':
      return roleMenuStore.adminRoleMenus;
    case 'STU':
      return roleMenuStore.stuRoleMenus;
    case 'TEACH':
      return roleMenuStore.teachRoleMenus;
    default:
      return [];
  }
};

// 处理复选框变化事件
const handleCheckChange = (data: any, checked: boolean) => {
  if (checked) {
    if (!selectedMenuIds.value.includes(data.id.toString())) {
      selectedMenuIds.value.push(data.id.toString());
    }
  } else {
    const index = selectedMenuIds.value.indexOf(data.id.toString());
    if (index > -1) {
      selectedMenuIds.value.splice(index, 1);
    }
  }
};

onMounted(async () => {
  await menuStore.fetchTreeMenus();
  for (const role of roles) {
    await roleMenuStore.fetchTreeRoleMenus(role);
  }
});

// 提交分配权限请求
const submitAssign = async () => {
  const params: DoAssignParams = {
    roleCode: currentRole.value,
    menuIdList: selectedMenuIds.value
  };

  try {
    await roleMenuStore.doAssign(params);
    dialogVisible.value = false;
  } catch (error) {
    showNotification('权限分配失败', true);
  }
};
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>    